package com.xbongbong.paas.util;


import com.alibaba.fastjson.JSON;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DateTimeEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.imports.CellValuePojo;
import com.xbongbong.paas.pojo.imports.MergeRegionRangePojo;
import com.xbongbong.paas.pojo.vo.ImportPoJo;
import com.xbongbong.paas.service.HandleImportService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.export.ImportConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMergeCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMergeCells;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Excel工具类
 *
 * @author GuoJun.HU
 * @date 2019/4/29 14:42
 * @since V1.0
 */
public class ExcelUtil {

    private static HandleImportService handleImportService;

    private static final Logger LOG = LoggerFactory.getLogger(ExcelUtil.class);

    /**
     * 获取某一行row中每一列的值
     *
     * @param row       行
     * @param columnNum 列数
     * @return String[]
     * @author GuoJun.HU
     * @date 2019/5/8 15:42
     * @since V1.0
     */
    public static String[] getExcelRowValue(Row row, Integer columnNum) {
        String[] rowValueArray = new String[columnNum];
        String value;
        for (int columnIndex = 0; columnIndex < columnNum; columnIndex++) {
            // 遍历列 获取到row行每一列的值
            Cell cell = row.getCell(columnIndex);
            if (cell != null) {
                value = getCellValue(cell);
            } else {
                value = "";
            }
            rowValueArray[columnIndex] = value;
        }
        return rowValueArray;
    }

    /**
     * 获取单元格的值
     *
     * @param cell 单元格
     * @return String
     * @author GuoJun.HU
     * @date 2019/4/25 20:10
     * @since V1.0
     */
    public static String getCellValue(Cell cell) {
        if (Objects.isNull(cell)) {
            return "";
        }

        String value;
        switch (cell.getCellTypeEnum()) {
            case FORMULA:
                CellType cellValueType;
                try {
                    FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
                    CellValue cellValue = evaluator.evaluate(cell);
                    cellValueType = cellValue.getCellTypeEnum();
                } catch (Exception e) {
                    cellValueType = CellType.STRING;
                }
                try {
                    switch (cellValueType) {
                        case NUMERIC:
                            Double tempValue = cell.getNumericCellValue();
                            DecimalFormat df;
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                Date d = cell.getDateCellValue();
                                value = Objects.toString(DateTimeUtil.getInt(d));
                            } else if (Math.abs(tempValue - tempValue.longValue()) < ImportConstant.MIN_PRECISION) {
                                df = new DecimalFormat("#");
                                value = df.format(tempValue);
                            } else {
                                value = Objects.toString(tempValue, "");
                            }
                            break;
                        case STRING:
                            value = cell.getStringCellValue();
                            value = StringUtil.trim(value);
                            value = StringUtil.trimNewLines(value);
                            break;
                        default:
                            value = "";
                            break;
                    }
                } catch (Exception e) {
                    LOG.warn("excel formula error,value is %s" + cell.getCellFormula());
                    value = "";
                }
                break;
            case NUMERIC:
                Double tempValue = cell.getNumericCellValue();
                DecimalFormat df;
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    Date d = cell.getDateCellValue();
                    value = Objects.toString(DateTimeUtil.getInt(d));
                } /*else if (Math.abs(tempValue - tempValue.longValue()) < ImportConstant.MIN_PRECISION) {
                    df = new DecimalFormat("#");
                    value = df.format(tempValue);
                } */else {
//                    value = Objects.toString(tempValue, "");
                    String cellstr = cell.toString();
                    cell.setCellType(CellType.STRING);
                    value = cell.getStringCellValue();
                    if(value.indexOf(StringConstant.POINT) > -1) {
                        value = cellstr;
                    }
                }
                break;
            case STRING:
            case BLANK:
                value = cell.getStringCellValue();
                value = StringUtil.trim(value);
                value = StringUtil.trimNewLines(value);
                break;
            default:
                value = "";
                break;
        }

        return value;
    }

    /**
     * 获取合并单元格的值
     *
     * @param sheet  表格
     * @param row    行
     * @param column 列
     * @return String
     */
    public static String getMergedRegionValue(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress ca = sheet.getMergedRegion(i);
            int firstColumn = ca.getFirstColumn();
            int lastColumn = ca.getLastColumn();
            int firstRow = ca.getFirstRow();
            int lastRow = ca.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    Row fRow = sheet.getRow(firstRow);
                    Cell fCell = fRow.getCell(firstColumn);
                    return getCellValue(fCell);
                }
            }
        }
        return null;
    }

    /**
     * 如果excel是wps格式，获取合并单元格的cell时，cell会是null
     * 此时不能用该方法。请用{@link ExcelUtil#getMergedRegionValue(Sheet, int, int)}
     *
     * @param sheet 表格
     * @param cell  单元格
     * @return String
     */
    public static String getMergedRegionValue(Sheet sheet, Cell cell) {
        return getMergedRegionValue(sheet, cell.getRowIndex(), cell.getColumnIndex());
    }

    /**
     * 判断指定的单元格是否是合并单元格
     *
     * @param sheet  工作表
     * @param row    行下标
     * @param column 列下标
     * @return MergeRegionRangePojo
     */
    public static MergeRegionRangePojo isMergedRegion(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    return new MergeRegionRangePojo(true, firstRow, lastRow, firstColumn, lastColumn);
                }
            }
        }
        return new MergeRegionRangePojo(true, row, row, column, column);
    }

    /**
     * 如果excel是wps格式，获取合并单元格的cell时，cell会是null
     * 此时不能用该方法，请用{@link ExcelUtil#isMergedRegion(Sheet, int, int)}
     *
     * @param sheet 工作表
     * @param cell  单元格
     * @return MergeRegionRangePojo
     */
    public static MergeRegionRangePojo isMergedRegion(Sheet sheet, Cell cell) {
        int row = cell.getRowIndex();
        int column = cell.getColumnIndex();
        return isMergedRegion(sheet, row, column);
    }

    /**
     * 判断是否合并了行
     *
     * @param sheet  表格
     * @param row    行
     * @param column 列
     * @return boolean
     */
    public static boolean isMergedRow(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row == firstRow && row == lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断sheet页中是否含有合并单元格
     *
     * @param sheet 表格
     * @return boolean
     */
    public static boolean hasMerged(Sheet sheet) {
        return sheet.getNumMergedRegions() > 0;
    }

    /**
     * 合并单元格
     *
     * @param sheet    表格
     * @param firstRow 开始行
     * @param lastRow  结束行
     * @param firstCol 开始列
     * @param lastCol  结束列
     */
    public static void mergeRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
    }

    /**
     * 判断Row(行)是否存在空的单元格
     *
     * @param row 行
     * @return boolean
     */
    public static boolean rowContainEmptyCell(Row row) {
        if (row != null) {
            short lastCellNum = row.getLastCellNum();
            if (lastCellNum == 0) {
                // 如果不存在单元格则返回true
                return true;
            } else {
                for (int i = 0; i < lastCellNum; i++) {
                    Cell cell = row.getCell(i);
                    if (isEmptyCell(cell)) {
                        return true;
                    }
                }
            }
        } else {
            return true;
        }
        return false;
    }

    /**
     * 判断Sheet是否存在空行或存在空数据的行
     *
     * @param sheet 表格
     * @return boolean
     */
    public static boolean sheetContainEmptyRow(Sheet sheet) {
        if (sheet != null) {
            int lastRowNum = sheet.getLastRowNum();
            if (lastRowNum == 0) {
                // 如果不存在sheet则返回true
                return true;
            } else {
                for (int i = 0; i < lastRowNum; i++) {
                    Row row = sheet.getRow(i);
                    if (isEmptyRow(row)) {
                        return true;
                    }
                }
            }
        } else {
            return true;
        }
        return false;
    }

    /**
     * 获取表格中空行的行号
     *
     * @param sheet 表格
     * @return List
     */
    public static List<Integer> getEmptyRowNos(Sheet sheet) {
        List<Integer> list = new ArrayList<>();
        if (sheet != null) {
            int lastRowNum = sheet.getLastRowNum();
            if (lastRowNum != 0) {
                // 如果不存在sheet则返回true
                for (int i = 0; i < lastRowNum; i++) {
                    Row row = sheet.getRow(i);
                    if (isEmptyRow(row)) {
                        list.add(i);
                    }
                }
            }
        }
        return list;
    }

    /**
     * 判断Cell是否为空
     *
     * @param cell 单元格
     * @return boolean
     */
    public static boolean isEmptyCell(Cell cell) {
        return !StringUtils.hasText(getCellValue(cell));
    }

    /**
     * 判断是否为空行
     *
     * @param row 行
     * @return boolean
     * @author GuoJun.HU
     * @date 2019/4/26 11:04
     * @since V1.0
     */
    public static boolean isEmptyRow(Row row) {
        if (Objects.isNull(row)) {
            return true;
        }
        for (int cellIndex = row.getFirstCellNum(); cellIndex < row.getLastCellNum(); cellIndex++) {
            if (!isEmptyCell(row.getCell(cellIndex))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断某一行row从firstCellNum到lastCellNum的连续几个单元格是否都为空
     *
     * @param row          行
     * @param firstCellNum 起始索引
     * @param lastCellNum  结束索引
     * @return boolean
     * @author GuoJun.HU
     * @date 2019/4/26 11:04
     * @since V1.0
     */
    public static boolean isEmptyRow(Row row, Integer firstCellNum, Integer lastCellNum) {
        if (Objects.isNull(row)) {
            return true;
        }
        for (int cellIndex = firstCellNum; cellIndex < lastCellNum; cellIndex++) {
            if (!isEmptyCell(row.getCell(cellIndex))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 将数据写入某一行中
     *
     * @param row    行
     * @param values 数据
     * @author GuoJun.HU
     * @date 2019/4/29 16:14
     * @since V1.0
     */
    public static void addDataToRow(Row row, List<String> values) {
        if (values != null && !values.isEmpty()) {
            for (int i = 0; i < values.size(); i++) {
                Cell cell = row.createCell(i);
                cell.setCellValue(values.get(i));
            }
        }
    }

    /**
     * 合并数据的单元
     *
     * @param sheet     表格
     * @param importPoJoList
     * @param length    总长度，包括子表单的长度
     * @param firstRow  起始行
     * @param lastRow   结束行
     */
    public static void mergeDataCell(SXSSFSheet sheet, List<ImportPoJo> importPoJoList, int length, int firstRow, int lastRow) {
        // 用来记录未合并过的子表单
        int column = 0;
        CTWorksheet sheetX = sheet.getWorkbook().getXSSFWorkbook().getSheetAt(0).getCTWorksheet();
        for (int i = 0; i < length; i++) {
            if (i > importPoJoList.get(importPoJoList.size() - 1).getEnd()) {
                addMergedRegion(sheetX, new CellRangeAddress(firstRow, lastRow, i, i));
            } else {
                for (int j = column; j < importPoJoList.size(); j++) {
                    if (i == importPoJoList.get(j).getStart()) {
                        i = importPoJoList.get(j).getEnd();
                        column = j + 1;
                        break;
                    } else if (i < importPoJoList.get(j).getStart()) {
                        // 合并子表单之前和中间的单元格，上下合并（第二行和第三行合并）
                        addMergedRegion(sheetX, new CellRangeAddress(firstRow, lastRow, i, i));
                        break;
                    }
                }
            }
        }
    }

    private static void addMergedRegion(CTWorksheet sheetX, CellRangeAddress cellRangeAddress) {
        CTMergeCells ctMergeCells;
        if (sheetX.isSetMergeCells()) {
            ctMergeCells = sheetX.getMergeCells();
        } else {
            ctMergeCells = sheetX.addNewMergeCells();
        }
        CTMergeCell ctMergeCell = ctMergeCells.addNewMergeCell();
        ctMergeCell.setRef(cellRangeAddress.formatAsString());
    }

    /**
     * 非合并方式填充空cell
     * @param sheet
     * @param importPoJoList
     * @param length
     * @param firstRow
     * @param lastRow
     */
    public static void fillDataCell(SXSSFSheet sheet, List<ImportPoJo> importPoJoList, int length, int firstRow, int lastRow) {
        int index = 0;
        for (int i = 0; i < length; i++) {
            if (i > importPoJoList.get(importPoJoList.size() - 1).getEnd()) {
                String value = sheet.getRow(firstRow).getCell(i).getStringCellValue();
                if (StringUtil.isNotEmpty(value)) {
                    for (int k = firstRow + 1; k < lastRow; k++) {
                        sheet.getRow(k).createCell(i).setCellValue(value);
                    }
                }
            } else {
                for (int j = index; j < importPoJoList.size(); j++) {
                    int start = importPoJoList.get(j).getStart();
                    if (i == start) {
                        i = importPoJoList.get(j).getEnd();
                        index = j + 1;
                        break;
                    } else if (i < start) {
                        String value = sheet.getRow(firstRow).getCell(i).getStringCellValue();
                        if (StringUtil.isNotEmpty(value)) {
                            for (int k = firstRow + 1; k < lastRow; k++) {
                                sheet.getRow(k).createCell(i).setCellValue(value);
                            }
                        }
                        break;
                    }
                }
            }
        }
    }

    /**
     * 合并单元格
     *
     * @param sheet     表格
     * @param endNum    总长度，包括子表单的长度
     */
    public static void mergeSubTitleCell(SXSSFSheet sheet, List<ImportPoJo> importPoJoList, int startNum, int endNum, int firstRow, int lastRow) {
        int index = 0;
        for (int i = startNum; i < endNum; i++) {
            // 合并子表单之后的单元格，上下合并
            if (i > importPoJoList.get(importPoJoList.size() - 1).getEnd()) {
                sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, i, i));
            } else {
                for (int j = index; j < importPoJoList.size(); j++) {
                    ImportPoJo firstSub = importPoJoList.get(j);
                    int start = firstSub.getStart();
                    if (i == start) {
                        List<ImportPoJo> subImportPoJoList = firstSub.getImportPoJoList();
                        int end = firstSub.getEnd();
                        if (start < end) {
                            sheet.addMergedRegion(new CellRangeAddress(firstRow, firstRow, start, end));
                        }
                        if (subImportPoJoList != null && !subImportPoJoList.isEmpty()) {
                            mergeSubTitleCell(sheet, subImportPoJoList, start, end + 1, firstRow + 1, lastRow);
                        } else {
                            if (firstRow < lastRow - 1) {
                                for (int k = start; k <= end; k++) {
                                    sheet.addMergedRegion(new CellRangeAddress(firstRow + 1, lastRow, k, k));
                                }
                            }
                        }
                        i = end;
                        index = j + 1;
                        break;
                    } else if (i < start) {
                        // 合并子表单之前的单元格，上下合并
                        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, i, i));
                        break;
                    }
                }
            }
        }
    }

    /**
     * 设置标题
     *
     * @param wb    workBook
     * @param sheet sheet
     * @param name  标题
     */
    public static void setTitle(SXSSFWorkbook wb, SXSSFSheet sheet, String name) {
        // 创建单元格，并设置值表头居中
        SXSSFRow row = sheet.createRow(0);
        SXSSFCell cell = row.createCell(0);
        // 样式对象
        CellStyle titleStyle = wb.createCellStyle();
        // 垂直
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 水平
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        // 设置标题字体格式
        Font fontTitle = wb.createFont();
        // 设置字体大小
        fontTitle.setFontHeightInPoints(ImportConstant.FONT_SIZE);
        // 设置字体，是什么类型例如：Courier New
        fontTitle.setFontName(ImportConstant.FONT_COURIER_NEW);
        titleStyle.setFont(fontTitle);
        // 设置是否能够换行，能够换行为true
        titleStyle.setWrapText(false);
        cell.setCellStyle(titleStyle);
        cell.setCellValue(name);
    }

    /**
     * 设置子标题
     *
     * @param wb   workBook
     * @param cell 单元格
     */
    public static void setSubFormTitle(SXSSFWorkbook wb, SXSSFCell cell) {
        // 样式对象
        CellStyle titleStyle = wb.createCellStyle();
        // 垂直
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 水平
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        // 设置标题字体格式
        Font fontTitle = wb.createFont();
        // 设置字体，是什么类型例如：宋体
        fontTitle.setFontName(I18nMessageUtil.getMessage(ImportConstant.FONT_SONG));
        titleStyle.setFont(fontTitle);
        // 设置是否能够换行，能够换行为true
        titleStyle.setWrapText(false);
        cell.setCellStyle(titleStyle);
    }

    /**
     * excel 添加内容
     *
     * @param wb           目标excel
     * @param rowValueList  组数据
     * @param isErrorExcel 是否错误excel（错误excel，后续index加1）
     */
    public static void addExcelContent(Workbook wb, List<List<CellValuePojo>> rowValueList, boolean isErrorExcel, Map<String, Integer> titleIndexMap, List<FieldAttrEntityForImport> explainList, Integer businessType) throws XbbException {
        // 强制转换为SXSSFWorkbook
        SXSSFSheet sheet = ((SXSSFWorkbook) wb).getSheetAt(0);
        Integer rowNum = sheet.getLastRowNum();
        Integer mergeSize = rowValueList.size();
        Integer i = 0;
        Map<String, String> dateTypeTitleMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        String title = "";
        getDateTypeTitleMap(explainList, dateTypeTitleMap, title);
        String thirdParent;
        String secondParent;
        String parent;
        String deepTitle;
        String cellTitle;
        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setWrapText(true);
        Font font = wb.createFont();
        font.setColor(IndexedColors.RED.getIndex());
        cellStyle.setFont(font);
        for (List<CellValuePojo> valuePojos : rowValueList) {
            i++;
            SXSSFRow row = sheet.createRow(rowNum + i);
            SXSSFCell cell;
            for (CellValuePojo cellValuePojo : valuePojos) {
                Object value = cellValuePojo.getValue();
                parent = cellValuePojo.getParentTitle() == null ? "" : cellValuePojo.getParentTitle();
                secondParent = cellValuePojo.getSecondParentTitle() == null ? "" : cellValuePojo.getSecondParentTitle();
                thirdParent = cellValuePojo.getThirdParentTitle() == null ? "" : cellValuePojo.getThirdParentTitle();
                deepTitle = cellValuePojo.getTitle();
                cellTitle = thirdParent + secondParent + parent + deepTitle;
                Integer columnIndex = titleIndexMap.get(cellTitle);
                if (columnIndex == null || !titleIndexMap.containsKey(cellTitle)) {
                    continue;
                }
                // 第i+1格
                cell = row.createCell(columnIndex);
                if (isErrorExcel && columnIndex == 0) {
                    cell.setCellStyle(cellStyle);
                }
                if (!Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode()) && cellValuePojo.getParentTitle() == null && Objects.equals(i, mergeSize) && mergeSize > 1) {
                    CellRangeAddress cellAddresses = new CellRangeAddress(rowNum + 1, rowNum + mergeSize, columnIndex, columnIndex);
                    boolean canMerge = true;
                    List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
                    for (CellRangeAddress mergedRegion : mergedRegions) {
                        if (mergedRegion.intersects(cellAddresses)) {
                            canMerge = false;
                            break;
                        }
                    }
                    if (canMerge) {
                        sheet.addMergedRegion(cellAddresses);
                    }
                }
                if (dateTypeTitleMap.containsKey(cellTitle)) {
                    if (Objects.nonNull(value)) {
                        String dateType = dateTypeTitleMap.get(cellTitle);
                        Long time = StringUtil.StringToLong(value.toString() );
                        if (Objects.nonNull(time)) {
                            if (Objects.equals(dateType, DateTimeEnum.TIME.getType())) {
                                cell.setCellValue(DateTimeUtil.getStringEpochSecond(time, DateTimeUtil.SDFDate));
                            } else if (Objects.equals(dateType, DateTimeEnum.DATETIME.getType())) {
                                cell.setCellValue(DateTimeUtil.getStringEpochSecond(time, DateTimeUtil.SDFYMDHM));
                            }
                        } else {
                            cell.setCellValue(value.toString());
                        }
                    }
                } else if (value instanceof Integer) {
                    cell.setCellValue((Integer) value);
                } else if (value instanceof Float) {
                    cell.setCellValue((Float) value);
                } else if (value instanceof BigDecimal) {
                    cell.setCellValue(Objects.toString(value, ""));
                } else {
                    cell.setCellValue((String) value);
                }
            }
        }
    }

    /**
     * 获取时间类型的字段标题和所有标题
     *
     * @param explainList
     * @param dateTypeTitleMap
     * @param title
     */
    public static void getDateTypeTitleMap(List<FieldAttrEntityForImport> explainList, Map<String, String> dateTypeTitleMap,String title) {
        if (Objects.isNull(explainList)) {
            return;
        }
        for (FieldAttrEntityForImport fieldAttrEntityForImport : explainList) {
            if (Objects.equals(fieldAttrEntityForImport.getFieldType(), FieldTypeEnum.SUB_FORM.getType())) {
                List<FieldAttrEntityForImport> fieldAttrEntityForImportList = JSON.parseArray(JSON.toJSONString(fieldAttrEntityForImport.getSubForm().getItems()), FieldAttrEntityForImport.class);
                getDateTypeTitleMap(fieldAttrEntityForImportList, dateTypeTitleMap, title + fieldAttrEntityForImport.getAttrName());
            } else {
                if (Objects.equals(fieldAttrEntityForImport.getFieldType(), FieldTypeEnum.DATETIME.getType())) {
                    dateTypeTitleMap.put(title + fieldAttrEntityForImport.getAttrName(), fieldAttrEntityForImport.getDateType());
                }
            }
        }
    }

    /**
     * 添加错误数据到excel
     *
     * @param errorExcel 错误excel
     * @param errorMsg   错误信息
     * @param val        错误数据
     * @return Workbook
     * @author GuoJun.HU
     * @date 2019/5/21 17:31
     * @since V1.0
     */
    public static Workbook addError(Workbook errorExcel, String errorMsg, String[]val) {
        Sheet sheet = errorExcel.getSheetAt(0);
        int rowNum = sheet.getLastRowNum();
        Row row = sheet.createRow(rowNum + 1);
        //设置错误信息
        row.createCell(0).setCellValue(errorMsg);
        for (int i = 0; i < val.length; i++) {
            row.createCell(i + 1).setCellValue(val[i]);
        }
        return errorExcel;
    }

}